#!/bin/bash

# 数据库迁移脚本 (Linux/macOS)
# 用于手动执行数据库迁移

# 默认参数
CONNECTION_STRING="Host=localhost;Port=5432;Database=authservice;Username=postgres;Password=postgres"
ACTION="up"
VERSION=0

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        -c|--connection)
            CONNECTION_STRING="$2"
            shift 2
            ;;
        -a|--action)
            ACTION="$2"
            shift 2
            ;;
        -v|--version)
            VERSION="$2"
            shift 2
            ;;
        -h|--help)
            echo "用法: $0 [选项]"
            echo "选项:"
            echo "  -c, --connection STRING   数据库连接字符串"
            echo "  -a, --action STRING       操作类型 (up|down|list|validate)"
            echo "  -v, --version NUMBER      迁移版本号"
            echo "  -h, --help               显示帮助信息"
            exit 0
            ;;
        *)
            echo "未知参数: $1"
            exit 1
            ;;
    esac
done

echo "开始执行数据库迁移..."
echo "连接字符串: $CONNECTION_STRING"
echo "操作: $ACTION"

# 切换到项目目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_PATH="$SCRIPT_DIR/../AuthService.Api"
cd "$PROJECT_PATH" || exit 1

# 检查FluentMigrator工具
echo "检查FluentMigrator工具..."
if ! dotnet tool list -g | grep -q "fluentmigrator.dotnet.cli"; then
    echo "安装FluentMigrator工具..."
    dotnet tool install -g FluentMigrator.DotNet.Cli
fi

# 构建项目
echo "构建项目..."
dotnet build --configuration Release

if [ $? -ne 0 ]; then
    echo "错误: 项目构建失败"
    exit 1
fi

# 执行迁移
ASSEMBLY_PATH="bin/Release/net9.0/AuthService.Infrastructure.dll"

case "${ACTION,,}" in
    "up")
        echo "执行向上迁移..."
        if [ $VERSION -eq 0 ]; then
            dotnet fm migrate -p postgres -c "$CONNECTION_STRING" -a "$ASSEMBLY_PATH"
        else
            dotnet fm migrate -p postgres -c "$CONNECTION_STRING" -a "$ASSEMBLY_PATH" --version $VERSION
        fi
        ;;
    "down")
        if [ $VERSION -eq 0 ]; then
            echo "错误: 回滚操作必须指定版本号"
            exit 1
        fi
        echo "执行回滚到版本 $VERSION..."
        dotnet fm rollback -p postgres -c "$CONNECTION_STRING" -a "$ASSEMBLY_PATH" --version $VERSION
        ;;
    "list")
        echo "列出所有迁移..."
        dotnet fm list migrations -p postgres -c "$CONNECTION_STRING" -a "$ASSEMBLY_PATH"
        ;;
    "validate")
        echo "验证迁移..."
        dotnet fm validate -p postgres -c "$CONNECTION_STRING" -a "$ASSEMBLY_PATH"
        ;;
    *)
        echo "错误: 不支持的操作: $ACTION。支持的操作: up, down, list, validate"
        exit 1
        ;;
esac

if [ $? -eq 0 ]; then
    echo "数据库迁移执行成功!"
else
    echo "错误: 数据库迁移执行失败"
    exit 1
fi

echo "迁移完成!"
